package com.example.demo.controller;

import com.example.demo.model.History;
import com.example.demo.model.UserInfo;
import com.example.demo.mapper.HistoryMapper;
import com.example.demo.util.ConstVariable;
import com.example.demo.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/history")
public class HistoryController {
    
    @Autowired
    private HistoryMapper historyMapper;
    
    @GetMapping("/list")
    public JsonResult<List<History>> getHistory(
            HttpSession session,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "20") Integer limit) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return new JsonResult<>(0, "请先登录");
        }
        
        List<History> histories = historyMapper.getHistoryByUserId(userInfo.getId(), page * limit, limit);
        return new JsonResult<>(1, histories);
    }
    
    @PostMapping("/add")
    public JsonResult<Void> addHistory(
            HttpSession session,
            @RequestBody History history) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return new JsonResult<>(0, "请先登录");
        }
        
        history.setUserId(userInfo.getId());
        historyMapper.addHistory(history);
        return new JsonResult<>(1);
    }
    
    @DeleteMapping("/delete/{id}")
    public JsonResult<Void> deleteHistory(
            HttpSession session,
            @PathVariable Integer id) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return new JsonResult<>(0, "请先登录");
        }
        
        historyMapper.deleteHistory(id, userInfo.getId());
        return new JsonResult<>(1);
    }
    
    @DeleteMapping("/clear")
    public JsonResult<Void> clearHistory(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return new JsonResult<>(0, "请先登录");
        }
        
        historyMapper.clearHistory(userInfo.getId());
        return new JsonResult<>(1);
    }
} 